﻿using System;

namespace Mozi.Live.SDP
{
    /// <summary>
    /// 
    /// </summary>
    public class SDPRepeatTime
    {
        /// <summary>
        /// 间隔
        /// </summary>
        public uint Interval { get; set; }
        /// <summary>
        /// 延续时间
        /// </summary>
        public uint Duration { get; set; }
        /// <summary>
        /// 偏移时间
        /// </summary>
        public uint Offset { get; set; }
        /// <summary>
        /// 开始时间
        /// </summary>
        public uint StartTime { get; set; }

        //d - days(86400 seconds)
        //h - hours(3600 seconds)
        //m - minutes(60 seconds)
        //s - seconds(allowed for completeness)

        /// <summary>
        /// 解析重复时间信息
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static SDPRepeatTime Parse(string value)
        {
            SDPRepeatTime rt = new SDPRepeatTime();
            string[] items = value.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < items.Length; i++)
            {
                string it = items[i];
                char end = it[it.Length - 1];
                uint rate = 1;
                switch (end)
                {
                    case 'd':
                        rate = 86400;
                        break;
                    case 'h':
                        rate = 3600;
                        break;
                    case 'm':
                        rate = 60;
                        break;
                    case 's':
                        rate = 1;
                        break;
                    default: 
                        rate = 1;
                        break;
                }
                uint seconds;
                if (rate > 1)
                {
                    seconds = uint.Parse(it.Substring(0, it.Length - 1)) * rate;
                }
                else
                {
                    seconds = uint.Parse(it);
                }

                if (i == 0)
                {
                    rt.Interval = seconds;
                }else if (i == 1) {
                    rt.Duration = seconds;
                } else if (i == 2) {
                    rt.Offset = seconds;
                } else if (i == 3) {
                    rt.Offset = seconds;
                }
            }
            return rt;
        }

        /// <summary>
        /// 此处有两种写法 604800 3600 0 90000|7d 1h 0 25h
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return $"{Interval} {Duration} {Offset} {StartTime}";
        }
    }

}
